package com.nuanshui.framework.utils;

import com.nuanshui.framework.lang.SysStringUtils;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class PinyinUtil {

	public PinyinUtil() {
	}

	public static String str2Pinyin(final String str, String fill) {
		if(SysStringUtils.isEmpty(str)) return null;
		try {
			final StringBuilder sb = new StringBuilder();
			if (fill == null)
				fill = "";
			for (int i = 0; i < str.length(); i++) {
				final char c = str.charAt(i);
				if (c >= '\u4E00' && c <= '\u9FA5') {
					if (i > 0)
						sb.append(fill);
					String[] strs = PinyinHelper.toHanyuPinyinStringArray(
							str.charAt(i), format);
						sb.append(strs[0]);
				} else {
					sb.append(c);
				}
			}

			return sb.toString();
		} catch (final BadHanyuPinyinOutputFormatCombination e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String strFirst2Pinyin(final String str) {
		try {
			final StringBuilder sb = new StringBuilder();
			for (int i = 0; i < str.length(); i++) {
				final char c = str.charAt(i);
				if (c >= '\u4E00' && c <= '\u9FA5')
					sb.append(PinyinHelper.toHanyuPinyinStringArray(
							str.charAt(i), format)[0].charAt(0));
			}

			return sb.toString();
		} catch (final BadHanyuPinyinOutputFormatCombination e) {
			e.printStackTrace();
		}
		return null;
	}

	private static final HanyuPinyinOutputFormat format;

	static {
		format = new HanyuPinyinOutputFormat();
		format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		format.setVCharType(HanyuPinyinVCharType.WITH_V);
	}
}
